# -*- coding: utf-8 -*-
"""
Created on Mon Feb  4 17:38:49 2019
windows7
python3.6.3
Anaconda3->spyder
opencv3.4.5
代码参考《OpenCV3计算机视觉 Python语言实现》（第二版）
用于检测人，精度很低

@author: Administrator
"""


import cv2
import numpy as np

print(cv2.__version__)                    # 查看opencv的版本

def is_inside(o,i):
    ox,oy,ow,oh = o
    ix,iy,iw,ih = i
    return (ox > ix) and (oy > iy) and ((ox + ow) < (ix + iw)) and ((oy+ oh) < (iy + ih))

def draw_person(image,person):
    x,y,w,h = person
    cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),3)  #绘制矩形框
    
img = cv2.imread('timg.jpg',cv2.IMREAD_REDUCED_COLOR_2)
img2 = img.copy()         #使用图片的副本进行处理，避免有一些函数把原图改变

hog = cv2.HOGDescriptor() #使用梯度直方图的方法检测人
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) #使用支持矢量机进行检测

found, w = hog.detectMultiScale(img2,winStride=(8,8),scale=1.05)      #开始检测
#print(found)
found_filtered = []
for ri,r in enumerate(found):
    for qi,q in enumerate(found):
        if ri != qi and is_inside(r,q):
            break
        else:
            found_filtered.append(r)  #获取含有人脸的区域的坐标

for person in found_filtered:
    draw_person(img2,person)          #将检测到人脸的区域在原图中用矩形框框住

cv2.imshow('people detection',img2)
cv2.waitKey(0)
cv2.destroyAllWindows()




